package com.winai.launcher.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.bean.db.AlarmClockBean;

import java.util.Calendar;

public class AlarmManagerUtil {
    public static final String ALARM_ACTION = "com.winai.launcher.alarm.clock";

    /**
     * 说明：取消闹钟
     */
    public static void cancelAlarm(Context context, AlarmClockBean bean) {
        Intent intent = new Intent(ALARM_ACTION);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (bean.getAlarmClockType() == AlarmClockBean.WEEK) {
            //按星期循环设置闹钟
            String weeksStr = parseRepeat(bean.getRepeat(), 1);
            String[] weeks = weeksStr.split("，");
            for (int i = 0; i < weeks.length; i++) {
                PendingIntent pi = PendingIntent.getBroadcast(context, Integer.parseInt(bean.getId() + weeks[i]), intent, PendingIntent.FLAG_CANCEL_CURRENT);
                am.cancel(pi);
                LogUtils.e("取消闹钟，id = " + Integer.parseInt(bean.getId() + weeks[i]));
            }
        } else {
            PendingIntent pi = PendingIntent.getBroadcast(context, Integer.parseInt(bean.getId() + "0"), intent, PendingIntent.FLAG_CANCEL_CURRENT);
            am.cancel(pi);
            LogUtils.e("取消闹钟，id = " + Integer.parseInt(bean.getId() + "0"));
        }
    }

    /**
     * @param week 星期几  星期一：1；星期二：2；……；星期日：7；
     * @flag 周期性时间间隔的标志
     * ,flag = 0 表示一次性的闹钟
     * ,flag = 1 表示每天提醒的闹钟(1天的时间间隔)
     * ,flag = 2 表示按周每周提醒的闹钟（一周的周期性时间间隔）
     */
    private static void setAlarm(Context context, int week, long calMethod, AlarmClockBean bean) {
        Intent intent = new Intent(ALARM_ACTION);
        Bundle bundle = new Bundle();
        bundle.putSerializable("AlarmClockBean", bean);
        intent.putExtra("alarmBundle", bundle);
        PendingIntent sender = PendingIntent.getBroadcast(context, Integer.parseInt(bean.getId() + week), intent, PendingIntent
                .FLAG_CANCEL_CURRENT);

        LogUtils.e("设置闹钟，id = " + Integer.parseInt(bean.getId() + week) + "，triggerAtMillis = " + calMethod);

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        //如果设置的时间还没有到，则不需要增加周期
        am.setExact(AlarmManager.RTC_WAKEUP, calMethod, sender);
    }

    /**
     * 说明：设置闹钟
     */
    public static void setAlarm(Context context, AlarmClockBean bean) {
        String[] split = bean.getTime().split(":");
        int hour = 0, minute = 0, seconds = 0;
        if (split.length >= 2) {
            String s = split[0];
            String ss = split[1];
            hour = Integer.parseInt(s);
            minute = Integer.parseInt(ss);
        }
        if (split.length == 3) {
            String sss = split[2];
            seconds = Integer.parseInt(sss);
        }

        Calendar calendar = Calendar.getInstance();
//        if (!TextUtils.isEmpty(bean.getDay())) {
//            String[] split1 = bean.getDay().split("/");
//            int year = 0, month = 0, date = 0;
//            if (split1.length == 3) {
//                String s = split1[0];
//                String ss = split1[1];
//                String sss = split1[2];
//                year = Integer.parseInt(s);
//                month = Integer.parseInt(ss) - 1;
//                date = Integer.parseInt(sss);
//            }
//            calendar.set(year, month, date, hour, minute, seconds);
//        } else {
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get
                    (Calendar.DAY_OF_MONTH), hour, minute, seconds);
//        }
        if (bean.getAlarmClockType() == AlarmClockBean.WEEK) {
            //按星期循环设置闹钟
            String weeksStr = parseRepeat(bean.getRepeat(), 1);
            String[] weeks = weeksStr.split("，");

            long min = 0;
            int minWeek = 0;
            for (int i = 0; i < weeks.length; i++) {
                long calMethod = calMethod(Integer.parseInt(weeks[i]), calendar.getTimeInMillis());
                if (i == 0) {
                    min = calMethod;
                    minWeek = Integer.parseInt(weeks[i]);
                }
                if (calMethod < min) {
                    min = calMethod;
                    minWeek = Integer.parseInt(weeks[i]);
                }
            }
            long calMethod = calMethod(minWeek, calendar.getTimeInMillis());
            setAlarm(context, minWeek, calMethod, bean);
        } else {
            //按每天或者只响一次 设置闹钟
            long calMethod = calMethod(0, calendar.getTimeInMillis());
            setAlarm(context, 0, calMethod, bean);
        }
    }

    /**
     * @param week     传入的是周几
     * @param dateTime 传入的是时间戳（设置当天的年月日+从选择框拿来的时分秒）
     * @return 返回起始闹钟时间的时间戳
     */
    private static long calMethod(int week, long dateTime) {
        long time = 0;
        //week == 0表示是按天为周期性的时间间隔或者是一次性的，weekfalg非0时表示每周几的闹钟并以周为时间间隔
        long currentTimeMillis = System.currentTimeMillis();
        LogUtils.d("$#@D#D$:week = " + week + ",dateTime = " + dateTime + ",currentTimeMillis = " + currentTimeMillis);
        if (week != 0) {
            Calendar c = Calendar.getInstance();
            int currentWeek = c.get(Calendar.DAY_OF_WEEK);
            if (1 == currentWeek) {
                currentWeek = 7;
            } else if (2 == currentWeek) {
                currentWeek = 1;
            } else if (3 == currentWeek) {
                currentWeek = 2;
            } else if (4 == currentWeek) {
                currentWeek = 3;
            } else if (5 == currentWeek) {
                currentWeek = 4;
            } else if (6 == currentWeek) {
                currentWeek = 5;
            } else if (7 == currentWeek) {
                currentWeek = 6;
            }
            LogUtils.d("$#@D#D$:week = " + week + ",currentWeek = " + currentWeek);
            if (week == currentWeek) {
                if (dateTime > currentTimeMillis) {
                    time = dateTime;
                    LogUtils.d("$#@D#D$:week == currentWeek && dateTime > currentTimeMillis,time = " + time);
                } else {
                    time = dateTime + 7 * 24 * 3600 * 1000;
                }
            } else if (week > currentWeek) {
//                if (dateTime > currentTimeMillis) {
//                    time = dateTime;
//                } else {
                    time = dateTime + (week - currentWeek) * 24 * 3600 * 1000;
//                }
            } else {
                time = dateTime + (week - currentWeek + 7) * 24 * 3600 * 1000;
            }
        } else {
            if (dateTime > currentTimeMillis) {
                time = dateTime;
            } else {
                time = dateTime + 24 * 3600 * 1000;
            }
        }
        LogUtils.d("$#@D#D$:time = " + time);
        return time;
    }

    /**
     * @param repeat 解析二进制闹钟周期
     * @param flag   flag=0返回带有汉字的星期一，星期二cycle等，flag=1,返回数字的字符串1，2，3weeks等
     * @return
     */
    public static String parseRepeat(int repeat, int flag) {
        String cycle = "";
        String weeks = "";
        if (repeat == 0) {
            repeat = 127;
        }
        if (repeat % 2 == 1) {
            cycle = "星期一";
            weeks = "1";
        }
        if (repeat % 4 >= 2) {
            if ("".equals(cycle)) {
                cycle = "星期二";
                weeks = "2";
            } else {
                cycle = cycle + "，" + "星期二";
                weeks = weeks + "，" + "2";
            }
        }
        if (repeat % 8 >= 4) {
            if ("".equals(cycle)) {
                cycle = "星期三";
                weeks = "3";
            } else {
                cycle = cycle + "，" + "星期三";
                weeks = weeks + "，" + "3";
            }
        }
        if (repeat % 16 >= 8) {
            if ("".equals(cycle)) {
                cycle = "星期四";
                weeks = "4";
            } else {
                cycle = cycle + "，" + "星期四";
                weeks = weeks + "，" + "4";
            }
        }
        if (repeat % 32 >= 16) {
            if ("".equals(cycle)) {
                cycle = "星期五";
                weeks = "5";
            } else {
                cycle = cycle + "，" + "星期五";
                weeks = weeks + "，" + "5";
            }
        }
        if (repeat % 64 >= 32) {
            if ("".equals(cycle)) {
                cycle = "星期六";
                weeks = "6";
            } else {
                cycle = cycle + "，" + "星期六";
                weeks = weeks + "，" + "6";
            }
        }
        if (repeat / 64 == 1) {
            if ("".equals(cycle)) {
                cycle = "星期日";
                weeks = "7";
            } else {
                cycle = cycle + "，" + "星期日";
                weeks = weeks + "，" + "7";
            }
        }

        return flag == 0 ? cycle : weeks;
    }
}
